import { createApp, watch } from "vue";
import Dialog from "./dialog.vue";
export const showDialog = (options: any): Promise<any> => {
  const messageBoxApp = createApp(Dialog, options);
  return new Promise((resolve, reject) => {
    createDialog(messageBoxApp, { resolve, reject });
  });
};

const createDialog = (app: any, { resolve, reject }: any) => {
  const fragement = document.createDocumentFragment(); //是用来创建一个虚拟的节点对象，或者说，是用来创建文档碎片节点。它可以包含各种类型的节点，在创建之初是空的。
  const vm = app.mount(fragement);
  document.body.appendChild(fragement);
  vm.setVisible(true);
  watch(
    () => vm.visible,
    (visible) => {
      if (!visible) {
        hideDialog(app);
      }
    }
  );
  resolve({ app, vm });
};

export const hideDialog = (app: any, vm?: any) => {
  if (vm) {
    vm.setVisible(false);
  }
  setTimeout(() => {
    app.unmount();
  }, 500);
};
